<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="第6章 Token与HTTPBasic验证 —— 用令牌来管理用户, 湮灭星空,博客,Python,后端">
    <meta name="description" content="在我的TP5课程里，我们使用令牌的方式是服务器缓存的方式。那么在Python Flask中我们换一种令牌的发放方式。我们将用户的信息加密后作为令牌返回到客户端，客户端在访问服务器API时必须以HTTP Basic的方式携带令牌，我们再读取令">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>第6章 Token与HTTPBasic验证 —— 用令牌来管理用户 | 湮灭星空</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<link rel="alternate" href="/atom.xml" title="湮灭星空" type="application/atom+xml">
</head>

<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper head-container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">湮灭星空</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">湮灭星空</div>
        <div class="logo-desc">
            
            天下寥寥，苍生涂涂，诸子百家，唯我纵横
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/19.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        第6章 Token与HTTPBasic验证 —— 用令牌来管理用户
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/python/">
                                <span class="chip bg-color">python</span>
                            </a>
                        
                            <a href="/tags/flask/">
                                <span class="chip bg-color">flask</span>
                            </a>
                        
                            <a href="/tags/restful/">
                                <span class="chip bg-color">restful</span>
                            </a>
                        
                            <a href="/tags/api/">
                                <span class="chip bg-color">api</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/ginger/" class="post-category">
                                ginger
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-04-12
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2019-12-06
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    2k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    8 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>在我的TP5课程里，我们使用令牌的方式是服务器缓存的方式。那么在Python Flask中我们换一种令牌的发放方式。我们将用户的信息加密后作为令牌返回到客户端，客户端在访问服务器API时必须以HTTP Basic的方式携带令牌，我们再读取令牌信息后，将用户信息存入到g变量中，共业务代码全局使用…</p>
<h3 id="6-1-token概述"><a class="header-anchor" href="#6-1-token概述"></a>6-1 Token概述</h3>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-051940.jpg" alt="image-20190116135555431"></p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-051941.jpg" alt="image-20190102121307227"></p>
<h3 id="6-2-获取token令牌"><a class="header-anchor" href="#6-2-获取token令牌"></a>6-2 获取Token令牌</h3>
<p>理论上来说 get_token 的 HTTP 动词应该设为 get，但是由于获取 token 需要传入账号和密码，所以这里要使用 POST 方法。此外相对于 get 方法，post 方法的传参相对安全。如果使用 get 的方式来传递用户的账号和密码，我们只能够把这两个参数放在 url 后面的？（问号）里作为查询参数来传递，但是如果使用post 的话，我们就可以把账号和密码放到 HTTP 的 body 里面来传递。</p>
<p>先编写 ginger/app/api/v1/token.py，思路：</p>
<ol>
<li>创建 token 红图，将 token 红图注册到 v1蓝图中去</li>
<li>注册 token 路由，使用 POST 方法</li>
<li>实例化 ClientForm，验证 validate_for_api（验证数据格式）</li>
<li>使用 promise 辨别客户端类型</li>
<li>使用 promise 验证客户端提交的账户密码，查询用户返回用户 id</li>
<li>生成 token，使用 TimedJSONWebSignatureSerializer 序列化器生成 token<br>
生成的 token 是byte 类型的字符串，需要使用 <code>decode('ascii')</code>解码</li>
<li>将 token 序列化返回，并返回 HTTP 状态码</li>
</ol>
<pre><code class="language-python">from flask import current_app, jsonify

from app.libs.enums import ClientTypeEnum
from app.libs.red_print import RedPrint
from app.models.user import User
from app.validators.forms import ClientForm
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

api = RedPrint('token')


@api.route('', methods=['POST'])
def get_token():
    form = ClientForm().validate_for_api()
    promise = {
        ClientTypeEnum.USER_EMAIL: User.verify_by_email,
        ClientTypeEnum.USER_MOBILE: User.verify_by_mobile,
        ClientTypeEnum.USER_MINA: User.verify_by_mina,
        ClientTypeEnum.USER_WX: User.verify_by_wx,
    }
    identity = promise[ClientTypeEnum(form.type.data)](form.account.data, form.secret.data)
    expiration = current_app.config['TOKEN_EXPIRATION']
    token = generate_auth_token(identity['uid'], form.type.data, None, expiration)
    t = {
        'token': token.decode('ascii')
    }
    return jsonify(t), 201


def generate_auth_token(uid, ac_type, scope=None, expiration=7200):
    s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
    return s.dumps({
        'uid': uid,
        'token': ac_type.value
    })
</code></pre>
<p>在 User 模型内编写验证客户端账户密码的方法：</p>
<ol>
<li>先查询用户</li>
<li>如果用户不存在，返回找不到</li>
<li>使用 check_password_hash 比对客户端传入的密码与数据库中保存的密码</li>
<li>如果用户密码错误，返回授权失败</li>
</ol>
<pre><code class="language-python">@staticmethod
    def verify_by_email(email, password):
        user = User.query.filter_by(email=email).first()
        if not user:
            raise NotFound(msg='user not found')
        if not user.check_password(password):
            raise AuthFailed()
        return {'uid': user.id}

    def check_password(self, raw):
        if not self.password:
            return False
        return check_password_hash(self.password, raw)
</code></pre>
<p>在配置文件中配置 TOKEN_EXPIRATION，这是作为开发用途，所以过期时间比较长，正式上线之后过期时间设置为两小时比较合适</p>
<pre><code class="language-python">TOKEN_EXPIRATION = 30 * 24 * 3600
</code></pre>
<h3 id="6-3-token的用处"><a class="header-anchor" href="#6-3-token的用处"></a>6-3 Token的用处</h3>
<h3 id="6-4-auth拦截器执行流程"><a class="header-anchor" href="#6-4-auth拦截器执行流程"></a>6-4 @auth拦截器执行流程</h3>
<p>本节主要了解一下 @auth.login_required 和 @auth.verify_password 两个装饰器的作用。</p>
<p>现在需要保护的视图函数前打上 @auth.login_required 装饰器，</p>
<pre><code class="language-python">@api.route('', methods=['GET'])
@auth.login_required
def get_user():
    return 'user'
</code></pre>
<p>再在 ginger/app/libs/token_auth.py 内为 verify_password 函数打上 @verify_password 装饰器。</p>
<pre><code class="language-python">from flask_httpauth import HTTPBasicAuth

auth = HTTPBasicAuth()

@auth.verify_password
def verify_password(account, password):
    pass
</code></pre>
<p>@auth 拦截器的请求流程：</p>
<ol>
<li>先访问到 get_user 视图函数，</li>
<li>再转到 verify_password 函数，
<ul>
<li>如果 verify_password 函数返回 True，则返回到 get_user 视图函数内执行 get_user 的内容，最后返回给客户端</li>
<li>否则，直接给客户端返回 Unauthorized Access</li>
</ul>
</li>
</ol>
<h3 id="6-5-httpbasicauth基本原理"><a class="header-anchor" href="#6-5-httpbasicauth基本原理"></a>6-5 HTTPBasicAuth基本原理</h3>
<p>在 verify_password 函数中需要接收 account、password 两个参数，那么如何获取这两个参数呢？</p>
<p>之前在 ClientForm 中已经可以接收到客户端传来的 account、password 了，这种接收账号和密码的方式是我们自己定义的一种方式，毫无疑问账号和密码只是两个普通的参数，当然可以通过自定义的方式传送到服务器。</p>
<p>除了自定义的方式传参方式，HTTP 这种协议本身就有一种规范，这种规范允许我们传递账号和密码。HTTP 自带的发送账号和密码的方式有很多种，其中一种就是 HTTPBasicAuth，还有其他的诸如 HTTPDigestAuth 等其他规范。</p>
<p>HTTPBasicAuth 规定：</p>
<p>必须将账号、密码放在 HTTP 的 Headers 里面。（之前 ClientForm 是将账户和密码放在 HTTP 的 body 里面发送的）</p>
<p>HTTP 的头是一组一组的 key：value 的键值对。</p>
<ul>
<li>需要在 HTTP 的头中设置一个固定的 key，key 的名字叫做 <mark>Authorization</mark>，</li>
<li>key 的 value 是 <mark>basic base64(account：password)</mark></li>
</ul>
<blockquote>
<p>注意：</p>
<ol>
<li>
<p>前面是 basic + 一个空格</p>
</li>
<li>
<p>base64() 表示 base64 加密</p>
</li>
</ol>
</blockquote>
<p>postman 演示：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-051943.jpg" alt="image-20190103103220098"></p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-051944.jpg" alt="image-20190103103350851"></p>
<p>只要 HTTP 传入的参数符合规范，verify_password 函数就能正确的获到账户和密码。</p>
<blockquote>
<p>面试问题：</p>
<p>以上就是 HTTPBasicAuth 的基本原理和传递规范，关于 HTTP 的协议在很多服务器面试的时候都会经常问到，这种 HTTPBasicAuth 面试的问题也是非常多的，一定要熟记。</p>
</blockquote>
<h3 id="6-6-以basicauth的方式发送token"><a class="header-anchor" href="#6-6-以basicauth的方式发送token"></a>6-6 以BasicAuth的方式发送Token</h3>
<p>第一次登陆的时候需要账户密码，但是后续的访问需要的是 token 而不是 account、password，但是我们可以通过相同的方式传递 token，我们只需要将 token 当做 account 来传就可以了，密码不传或者传空。</p>
<h3 id="6-7-验证token"><a class="header-anchor" href="#6-7-验证token"></a>6-7 验证Token</h3>
<ol>
<li>
<p>我们需要编写 verify_auth_token 函数来验证 token</p>
<ol>
<li>
<p>使用 SECRET_KEY 实例化一个序列化器</p>
</li>
<li>
<p>使用 <code>s.loads(token)</code>将 token 反序列化赋给 data</p>
<ul>
<li>如果遇到 BadSignature，则表示 token 错误，返回 token 非法的错误信息</li>
<li>如果遇到 SignatureExpired，则表示 token 过期，返回 token 过期的错误信息</li>
</ul>
</li>
<li>
<p>从 data 中取出 uid 和 ac_type（这两个是之前我们生产 token 的时候放进去的）</p>
</li>
<li>
<p>然后将 uid 和 ac_type 打包返回，我们可以选择元组、字典的方式返回，但是最好的方式是使用一个对象式的结构返回回去：</p>
<pre><code class="language-python">User = namedtuple('User', ['uid', 'ac_type', 'scope'])
</code></pre>
<p>这里使用 namedtuple 有什么优势，我们在后面时候 User 对象的时候就知道了。</p>
</li>
</ol>
</li>
<li>
<p>将 verify_auth_token 的返回值赋给 user_info</p>
</li>
<li>
<p>如果 user_info 为空，则表示验证失败，返回 False</p>
</li>
<li>
<p>否则将 user_info 保存到 g 变量的 user 属性中。<br>
（这个 g 变量就跟 flask 的 request 对象是一样的，它们都是一个代理模式的实现，至于 g 变量怎么用后面再说，线程安全。）</p>
</li>
</ol>
<pre><code class="language-python">from collections import namedtuple

from flask import current_app, g
from flask_httpauth import HTTPBasicAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired

from app.libs.error_code import AuthFailed

auth = HTTPBasicAuth()
User = namedtuple('User', ['uid', 'ac_type', 'scope'])


@auth.verify_password
def verify_password(token, password):
    user_info = verify_auth_token(token)
    if not user_info:
        return False
    else:
        g.user = user_info
        return True


def verify_auth_token(token):
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
    except BadSignature:
        raise AuthFailed(msg='token is invalid', error_code=1002)
    except SignatureExpired:
        raise AuthFailed(msg='token is expired', error_code=1003)
    uid = data['uid']
    ac_type = data['type']
    return User(uid, ac_type, '')
</code></pre>
<h3 id="6-8-重写first-or-404与get-or-404"><a class="header-anchor" href="#6-8-重写first-or-404与get-or-404"></a>6-8 重写first_or_404与get_or_404</h3>
<p>前面对 get_user 视图函数的保护工作已经做完了，现在我们来正式编写 get_user 视图函数。</p>
<ol>
<li>查询用户</li>
<li>判断查询的用户是否存在，不存在则返回 NotFound</li>
</ol>
<pre><code class="language-python">@api.route('/&lt;int:uid&gt;', methods=['GET'])
@auth.login_required
def get_user(uid):
    user = User.query.get(uid)
    if not user:
        raise NotFound()
    return user
</code></pre>
<p>那么问题来了，我们每次查询数据库的时候都需要判断查询的内容是否存在，这是一件很麻烦的事情。我们可不可以不写呢？好在有一个 get_or_404 方法，但是 get_or_404 方法放回的是系统内部的错误信息，并不是 APIException，不是 APIException 的话那么返回的格式就不是我们要求的 JSON 格式，所以我们需要重写 get_or_404 方法，让它返回 APIException。get_or_404 是 query 的方法，我们找到 query 在 ginger/models/base.py 中：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-051947.jpg" alt="image-20190103120544414"></p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-051948.jpg" alt="image-20190103120504021"></p>
<p>我们按照 BaseQuery.get_or_404 仿写就可以了，其他都一样，只是<code>abort(404)</code>那里改成 <code>raise APIException</code>就可以了。同理仿写 first_or_404。</p>
<pre><code class="language-python">class Query(BaseQuery):
    def filter_by(self, **kwargs):
        if 'status' not in kwargs.keys():
            kwargs['status'] = 1
        return super(Query, self).filter_by(**kwargs)

    def get_or_404(self, ident):
        rv = self.get(ident)
        if not rv:
            raise NotFound()
        return rv

    def first_or_404(self):
        rv = self.first()
        if not rv:
            raise NotFound()
        return rv
</code></pre>
<p>以下是需要修改的地方：</p>
<ol>
<li>
<p>第一处<img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-051950.jpg" alt="image-20190103120927580">改成：<img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-051956.jpg" alt="image-20190103121026545"></p>
</li>
<li>
<p>第二处<br>
<img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-051958.jpg" alt="image-20190103121229875"></p>
<p>改成：<br>
<img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-051959.jpg" alt="image-20190103121303485"></p>
</li>
</ol>

<div id="gitalk-container"></div>
<script src="https://cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script><link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"><script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

		<script>
		var gitalkConfig = {"clientID":"9eb5bc3ac1e1ff3ddac0","clientSecret":"4b7ae28042282281295075c2bf0c97ff1791cfeb","repo":"HexoBlogComments","owner":"Annihilater","admin":["Annihilater"],"distractionFreeMode":false};
	    gitalkConfig.id = md5(location.pathname);
		var gitalk = new Gitalk(gitalkConfig);
	    gitalk.render("gitalk-container");
	    </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn" rel="external nofollow noreferrer">湮灭星空</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn/2019/04/12/python-flask-gou-jian-ke-kuo-zhan-de-restful-api/di-6-zhang-token-yu-httpbasic-yan-zheng-yong-ling-pai-lai-guan-li-yong-hu/">https://www.klause.cn/2019/04/12/python-flask-gou-jian-ke-kuo-zhan-de-restful-api/di-6-zhang-token-yu-httpbasic-yan-zheng-yong-ling-pai-lai-guan-li-yong-hu/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/python/">
                                    <span class="chip bg-color">python</span>
                                </a>
                            
                                <a href="/tags/flask/">
                                    <span class="chip bg-color">flask</span>
                                </a>
                            
                                <a href="/tags/restful/">
                                    <span class="chip bg-color">restful</span>
                                </a>
                            
                                <a href="/tags/api/">
                                    <span class="chip bg-color">api</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/04/12/python-flask-gou-jian-ke-kuo-zhan-de-restful-api/di-5-zhang-li-jie-wtforms-bing-ling-huo-gai-zao-ta/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/14.jpg" class="responsive-img" alt="第5章 理解WTForms并灵活改造她">
                        
                        <span class="card-title">第5章 理解WTForms并灵活改造她</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            WTForms其实是非常强大的验证插件。但很多同学对WTForms的理解仅仅停留在“验证表单”上。那WTForms可以用来做API的参数验证码？完全可以，但这需要你灵活的使用它，对它做出一些“改变”
5-1 重写WTForms 一
原因：

                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-04-12
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/ginger/" class="post-category">
                                    ginger
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/python/">
                        <span class="chip bg-color">python</span>
                    </a>
                    
                    <a href="/tags/flask/">
                        <span class="chip bg-color">flask</span>
                    </a>
                    
                    <a href="/tags/restful/">
                        <span class="chip bg-color">restful</span>
                    </a>
                    
                    <a href="/tags/api/">
                        <span class="chip bg-color">api</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/04/12/python-flask-gou-jian-ke-kuo-zhan-de-restful-api/di-7-zhang-mo-xing-dui-xiang-de-xu-lie-hua/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/15.jpg" class="responsive-img" alt="第7章 模型对象的序列化">
                        
                        <span class="card-title">第7章 模型对象的序列化</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            最适合Python JSON序列化的是dict字典类型，每一种语言都有其对应的数据结构用来对应JSON对象，比如在PHP中是它的数组数据结构。而Python是用字典来对应JSON的。如果我们想直接序列化一个对象或者模型对象，那么最笨的办法是
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2019-04-12
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/ginger/" class="post-category">
                                    ginger
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/python/">
                        <span class="chip bg-color">python</span>
                    </a>
                    
                    <a href="/tags/flask/">
                        <span class="chip bg-color">flask</span>
                    </a>
                    
                    <a href="/tags/restful/">
                        <span class="chip bg-color">restful</span>
                    </a>
                    
                    <a href="/tags/api/">
                        <span class="chip bg-color">api</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">199.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "6";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn" target="_blank">皖ICP备18005729号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Annihilater" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:yanmiexingkong@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>





    <a href="https://twitter.com/" class="tooltipped" target="_blank" data-tooltip="关注我的Twitter: https://twitter.com/" data-position="top" data-delay="50">
        <i class="fab fa-twitter"></i>
    </a>







    <a href="https://www.zhihu.com/" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
